package com.fafa.swing.base;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: JProgressBarDemo1
 * @date Date : 2019年11月24日 21:58
 */
public class JProgressBarDemo1 implements ActionListener,ChangeListener {

    JFrame jFrame = null;
    JProgressBar progressBar;
    JLabel label;
    Timer timer;
    JButton button;

    public static void main(String[] args) {
        new JProgressBarDemo1();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button){
            timer.start();
        }
        if (e.getSource() == timer){
            int value = progressBar.getValue();
            if (value < 100){
                progressBar.setValue(++value);
            }else{
                timer.stop();
                jFrame.dispose();
            }
        }
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        int value = progressBar.getValue();
        if (e.getSource() == progressBar){
            label.setText("目前进度已经完成："+Integer.toString(value)+"%");
            label.setForeground(Color.blue);
        }
    }

    public JProgressBarDemo1(){
        jFrame = new JFrame("软件安装");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = jFrame.getContentPane();
        label = new JLabel("    ",JLabel.CENTER);
        progressBar = new JProgressBar();
        progressBar.setOrientation(JProgressBar.HORIZONTAL);
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        progressBar.addChangeListener(this);    //添加事件监听器
        //设置进度条的几何形状
        progressBar.setPreferredSize(new Dimension(300,20));
        progressBar.setBorderPainted(true);
        progressBar.setBackground(Color.pink);
        //添加启动按钮
        JPanel panel = new JPanel();
        button = new JButton("安装");
        button.setForeground(Color.blue);
        //添加事件监听器
        button.addActionListener(this);
        panel.add(button);
        timer = new Timer(100,this);    //创建一个计时器，计时间隔为100毫秒
        //把组件添加到frame中
        contentPane.add(label,BorderLayout.NORTH);
        contentPane.add(progressBar,BorderLayout.CENTER);
        contentPane.add(button,BorderLayout.SOUTH);
        jFrame.pack();
        jFrame.setLocation(600,400);
        jFrame.setVisible(true);

    }
}
